//
//  BIDMeetingDetailViewController.m
//  JuanChengOA
//
//  Created by mal on 2017/7/25.
//  Copyright © 2017年 mal. All rights reserved.
//

//已发活动详情
static NSString *sentActivityDetailURL = @"noticeAndroid!viewActivity.action";
//已收活动详情
static NSString *receivedActivityDetailURL = @"noticeAndroid!viewReceiveActivity.action";
//删除已收活动
static NSString *deleteReceivedActivityURL = @"noticeAndroid!dropActivityReply.action";
//删除已发活动
static NSString *deleteSentActivityURL = @"noticeAndroid!dropActivity.action";
//回复已收活动
static NSString *replyActivityURL = @"noticeAndroid!replyActivity.action";

#import "BIDActivityDetailViewController.h"
#import "BIDActivityDetailCell.h"
#import "BIDMenuView.h"
#import "BIDReplyView.h"
#import "BIDReplyListViewController.h"
#import "BIDReceiveConditionForActivityViewController.h"
#import "BIDShowPhotoViewII.h"
#import "BIDActivityDetailFooterView.h"
#import "BIDBrowserImageViewController.h"

@interface BIDActivityDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, BIDReplyViewDelegate, BIDMenuViewDelegate, UIAlertViewDelegate, BIDActivityDetailFooterViewDelegate>
{
    NSArray *_dataSourceArr;
    BIDActivityDetailCell *_tempCell;
    BOOL _isRegister;
    //UIView *_footerView;
    //
    BOOL _bShowMenu;
    BIDMenuView *_menuView;
    BIDReplyView *_replyView;
    BIDShowPhotoViewII *_showPhotoView;
    BIDActivityDetailFooterView *_footerView;
}
@end

@implementation BIDActivityDetailViewController
@synthesize isSent;
@synthesize activityID;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"活动详情";
    _dataSourceArr = @[];
    _tempCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDActivityDetailCell" owner:self options:nil] lastObject];
    _tableView.allowsSelection = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(functionHandler)];
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _replyView = [[BIDReplyView alloc] initWithFrame:CGRectMake(0, -screenSize.height, 0, 0)];
    _replyView.titleLabel.text = @"写回复";
    _replyView.delegate = self;
    //
    _footerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDActivityDetailFooterView" owner:self options:nil] lastObject];
    _footerView.delegate = self;
    //
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData
{
    NSString *strRequestURL = @"";
    NSString *strPost = @"";
    if(isSent)
    {
        //已发
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], sentActivityDetailURL];
        strPost = [[NSString alloc] initWithFormat:@"id=%@", activityID];
    }
    else
    {
        //已收
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], receivedActivityDetailURL];
        strPost = [[NSString alloc] initWithFormat:@"id=%@", activityID];
    }
    
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if(responseDic)
            {
                NSDictionary *activityDic = nil;
                NSString *strAttendanceLeader = @"";
                NSArray *imgArr = nil;
                if(isSent)
                {
                    activityDic = responseDic[@"activity"];
                    imgArr = responseDic[@"activityImages"];
                    NSArray *leaderArr = activityDic[@"attendanceUsers"];
                    strAttendanceLeader = [leaderArr componentsJoinedByString:@","];
                }
                else
                {
                    activityDic = responseDic[@"noticeReply"][@"activity"];
                    imgArr = responseDic[@"noticeReply"][@"activityImages"];
                    NSArray *leaderArr = responseDic[@"noticeReply"][@"attendanceUsers"];
                    strAttendanceLeader = [leaderArr componentsJoinedByString:@","];
                }
                NSString *strTitle = activityDic[@"title"];
                NSString *strTime = activityDic[@"meetingTime"];
                NSString *strPlace = activityDic[@"meetingPlace"];
                NSString *strOrganizeDepartment = activityDic[@"organizeUnit"];
                NSString *strAttendanceDepartment = activityDic[@"attendanceUnit"];
                
                NSString *strContent = activityDic[@"content"];
                //
                _dataSourceArr = @[@{@"title":@"活动主题", @"content":strTitle},
                                   @{@"title":@"活动时间", @"content":strTime},
                                   @{@"title":@"活动地点", @"content":strPlace},
                                   @{@"title":@"承办单位", @"content":strOrganizeDepartment},
                                   @{@"title":@"出席单位", @"content":strAttendanceDepartment},
                                   @{@"title":@"出席领导", @"content":strAttendanceLeader},
                                   @{@"title":@"活动内容", @"content":strContent}];
                NSMutableArray *desImgArr = [NSMutableArray array];
                [imgArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
                    NSDictionary *dic = (NSDictionary *)obj;
                    NSString *strImgPath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"path"]];
                    [desImgArr addObject:strImgPath];
                }];
                NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[strContent dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
                [_footerView loadContent:strContent];
                [_footerView setImgArr:desImgArr];
                _tableView.tableFooterView = _footerView;
                [_tableView reloadData];
            }
        }
    }];
}

- (void)deleteHandler
{
    NSString *strRequestURL = @"";
    if(isSent)
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], deleteSentActivityURL];
    }
    else
    {
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], deleteReceivedActivityURL];
    }
    NSString *strPost = [[NSString alloc] initWithFormat:@"selectIds=%@", activityID];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            NSNumber *value = responseDic[@"isSuccess"];
            if([value intValue] == 1)
            {
                [self showAlertView:@"删除成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
            }
            else
            {
                [self showAlertView:@"删除失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
        }
    }];
}

- (void)alertViewHandler:(id)obj
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  更多
 */
- (void)functionHandler
{
    //弹出菜单
    if(!_menuView && !isSent)
    {
        NSArray *menuNameArr = @[@" 快捷回复", @" 回复        ", @" 删除        "];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        //menuWidth,menuHeight,triangleWidth,triangleHeight,triangleToRight
        BIDMenuAttribute menuAttribute = {120, 5, 10, 15, 14};
        int menuViewPosX = screenSize.width - 26 - (menuAttribute.menuWidth-menuAttribute.triangleToRight-menuAttribute.triangleWidth/2);
        int menuViewPosY = 2;
        NSArray *imgNameArr = @[@"menu_fast_reply.png", @"menu_reply.png", @"menu_delete.png"];
        _menuView = [[BIDMenuView alloc] initWithFrame:CGRectMake(menuViewPosX, menuViewPosY, menuAttribute.menuWidth, menuAttribute.menuHeight) menuNameArr:menuNameArr imgNameArr:nil menuAttribute:menuAttribute];
        _menuView.delegate = self;
    }
    if(!_menuView && isSent)
    {
        NSArray *menuNameArr = @[@" 接收情况", @" 删除        "];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        //menuWidth,menuHeight,triangleWidth,triangleHeight,triangleToRight
        BIDMenuAttribute menuAttribute = {120, 5, 10, 15, 14};
        int menuViewPosX = screenSize.width - 26 - (menuAttribute.menuWidth-menuAttribute.triangleToRight-menuAttribute.triangleWidth/2);
        int menuViewPosY = 2;
        NSArray *imgNameArr = @[@"menu_receive_condition.png",@"menu_delete.png"];
        _menuView = [[BIDMenuView alloc] initWithFrame:CGRectMake(menuViewPosX, menuViewPosY, menuAttribute.menuWidth, menuAttribute.menuHeight) menuNameArr:menuNameArr imgNameArr:nil menuAttribute:menuAttribute];
        _menuView.delegate = self;
    }
    if(!_bShowMenu)
    {
        _bShowMenu = YES;
        [self.view addSubview:_menuView];
    }
    else
    {
        _bShowMenu = NO;
        [UIView animateWithDuration:1.0f animations:^{
            //_menuView.transform = CGAffineTransformMakeScale(0.5f, 0.5f);
        } completion:^(BOOL bFinished){
            if(bFinished)
            {
                [_menuView removeFromSuperview];
            }
        }];
    }
}

//回复通知
- (void)replyNoticeWithContent:(NSString*)replyContent
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], replyActivityURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"noticeReply.id=%@&noticeReply.content=%@", activityID, replyContent];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id responseObj, NSString *errMsg){
        if(responseObj)
        {
            NSDictionary *responseDic = (NSDictionary*)responseObj;
            NSNumber *value = responseDic[@"isSuccess"];
            if([value intValue]==1)
            {
                [BIDGlobalMethods showAlertView:@"回复成功" buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"回复失败" buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
            }
        }
    }];
}

#pragma mark - BIDActivityDetailFooterViewDelegate
- (void)updateFooterView
{
    _tableView.tableFooterView = _footerView;
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] initWithNibName:@"BIDBrowserImageViewController" bundle:nil];
    vc.index = index;
    vc.imgArr = [[NSArray alloc] initWithArray:arr];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDReplyViewDelegate
- (void)replyWithContent:(NSString *)replyContent
{
    [self replyNoticeWithContent:replyContent];
}

#pragma mark - BIDMenuViewDelegate
- (void)selectMenuAtIndex:(int)index
{
    _bShowMenu = NO;
    if(!isSent)
    {
        switch(index)
        {
            case 0:
            {
                //快捷回复
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定回复此会议\"确认收到\"吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alertView.tag = 2;
                [alertView show];
            }
                break;
            case 1:
            {
                //回复
                [_replyView showTheView];
            }
                break;
            case 2:
            {
                //删除
                [self deleteHandler];
            }
                break;
        }
    }
    else
    {
        switch(index)
        {
            case 0:
            {
                //接收情况
                BIDReceiveConditionForActivityViewController *vc = [[BIDReceiveConditionForActivityViewController alloc] init];
                vc.noticeId = activityID;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1:
            {
                //删除
                [self deleteHandler];
            }
                break;
        }
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 2)
    {
        if(buttonIndex == 1)
        {
            //快捷回复
            [self replyNoticeWithContent:@"确认收到"];
        }
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count-1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDActivityDetailCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDActivityDetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSDictionary *dic = _dataSourceArr[row];
    detailCell.titleLabel.text = [[NSString alloc] initWithFormat:@"%@：%@", dic[@"title"], dic[@"content"]];
    cell = detailCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    NSDictionary *dic = _dataSourceArr[indexPath.row];
    _tempCell.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.frame)-16*2;
    _tempCell.titleLabel.text = [[NSString alloc] initWithFormat:@"%@:%@", dic[@"title"], dic[@"content"]];
    CGSize size = [_tempCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    height = size.height<44 ? 44 : size.height+1;
    return height;
}

@end
